package com.huatao.wx.handler;

import com.huatao.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveTextMsgHandler implements WcChatMsgHandler{

    @Resource
    private RedisUtil redisUtil;

    private static final String KEY_WORDS = "验证码";

    private static final String LOGIN_KEY = "loginCode";

    public ReceiveTextMsgHandler() {
    }

    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> msgMap) {
        log.info("接收到文本消息事件");
        String content = msgMap.get("content");
        if (!KEY_WORDS.equals(content)) {
            return "";
        }
        String fromUserName = msgMap.get("FromUserName");
        String toUserName = msgMap.get("ToUserName");
        Random random = new Random();
        int num = random.nextInt(1000);
        String numKey = redisUtil.buildKey(LOGIN_KEY, String.valueOf(num));
        redisUtil.setNx(numKey,fromUserName, 5L, TimeUnit.MINUTES);
        String numContent = "你当前的验证码是: " + num + "5分钟有效";
        String replyContent = "<xml>\n" +
            "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
            "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
            "  <CreateTime>12345678</CreateTime>\n" +
            "  <MsgType><![CDATA[text]]></MsgType>\n" +
            "  <Content><![CDATA["+ numContent +"]]></Content>\n" +
            "</xml>";
        return replyContent;
    }
}
